package com.xfb.springboot;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.io.File;

public class SpringBootApplication {
    public static void run() throws LifecycleException, ServletException {
        Tomcat tomcat = new Tomcat();
        //获取项目编译后的classes 路径
        String path = SpringBootApplication.class.getResource("/").getPath();

        //获取webapp 文件
        String filePath = new File("src/main/webapp").getAbsolutePath();

        //然后将webapp下的项目添加至tomcat的context容器（context对应一个运行的项目）
        Context context =tomcat.addWebapp("/",filePath); //参数1：一般是项目名 对应请求url中的项目名
        //webResourceRoot 用于加载 项目的class文件
        WebResourceRoot webResource = new StandardRoot(context);
        webResource.addPreResources(new DirResourceSet(webResource,"/WEB-INF/classes",path,"/"));

        tomcat.start();
        // 阻塞tomcat 等待前端连接
        tomcat.getServer().await();
    }
}
